from flask import Flask, request, redirect
import jwt
import json
app = Flask(__name__)

# SSO 配置
SSO_SERVER_LOGIN_URL = 'http://192.168.6.128:5000/authorize'
CALLBACK_URL = 'http://192.168.6.128:5001/callback'
SECRET_KEY = 'your_secret_key'

@app.route('/')
def index():
    # 检查本地是否有有效的令牌
    token = request.cookies.get('token')
    if token:
        try:
            # 验证令牌
            jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
            return 'Welcome to sub - device!'
        except jwt.InvalidTokenError:
            pass
    print(333333)
    # 重定向到 SSO 服务端进行认证
    data = f'{SSO_SERVER_LOGIN_URL}?redirect_uri={CALLBACK_URL}'

    return redirect(data)

@app.route('/callback')
def callback():
    token = request.args.get('token')
    if token:
        try:
            # 验证令牌
            decoded_token = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
            # 可以在这里进行设备注册校验等操作
            response = app.make_response(redirect('/'))
            response.set_cookie('token', token)
            return response
        except jwt.InvalidTokenError:
            return 'Authentication failed'
    return 'Authentication failed'

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=False, port=5001)